﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Sale.DTO;

namespace Sale.DataAccess.Repository
{
    public class CurrencyRepository : BaseRepository
    {
        public IEnumerable<CurrencyDTO> GetCurrencyList()
        {
            return Context.Currencies.AsEnumerable()
                .Select(e => EntityToDTO(e));
        }

        public CurrencyDTO GetCurrencyById(int id)
        {
            return EntityToDTO(GetEntity(id));
        }

        private Currency GetEntity(int id)
        {
            return Context.Currencies.SingleOrDefault(e => e.Id == id);
        }

        public CurrencyWithExchangeRateDTO GetCurrencyExchangeRate(int currencyId, DateTime from)
        {
            var cur = GetEntity(currencyId);

            var exchangeRate = cur.CurrencyExchangeRates
                .Where(e => e.Date <= from)
                .OrderByDescending(e => e.Date)
                .FirstOrDefault();


            var dto = new CurrencyWithExchangeRateDTO()
            {
                Id = cur.Id,
                CurrencyName = cur.CurrencyName,
                From = exchangeRate.Date.Value,
                ExchangeRateToVND = exchangeRate.ExchangeRateInVND.Value
            };

           
            return dto;
        }

        private CurrencyDTO EntityToDTO(Currency entity)
        {
            return ObjectMapper.MapSourceToDestination<Currency, CurrencyDTO>(entity);
        }
    }
}
